package com.quanquan.store.service;

import DTO.PageDTO;
import DTO.user.UserDTO;
import DTO.user.UserInfoDTO;
import com.quanquan.store.configBean.RabbitSender;
import com.quanquan.store.dto.ActivityApplyDTO;
import com.quanquan.store.dto.IdDTO;
import com.quanquan.store.entity.Activity;
import com.quanquan.store.entity.ActivityApply;
import com.quanquan.store.repository.ActivityApplyRepository;
import com.quanquan.store.repository.ActivityRepository;
import com.quanquan.store.request.ActivityApplyRequestBody;
import com.quanquan.store.request.CouponRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import utils.DateUtils;
import utils.StringUtil;
import utils.UUIDGenerator;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 功能描述:报名活动逻辑层
 *
 * @ClassName: ActivityApplyService
 * @Author: xiaoqianh丶
 * @Date: 2019-06-27 13:56
 * @Version: V1.0
 */
@Service
public class ActivityApplyService {


    private final ActivityApplyRepository activityApplyRepository;

    private final ActivityRepository activityRepository;


    private final RabbitSender rabbitSender;
    private final RestTemplate restTemplate;
    private final CouponService couponService;

    public ActivityApplyService(ActivityApplyRepository activityApplyRepository, ActivityRepository activityRepository, RabbitSender rabbitSender, RestTemplate restTemplate, CouponService couponService) {
        this.activityApplyRepository = activityApplyRepository;
        this.activityRepository = activityRepository;
        this.rabbitSender = rabbitSender;
        this.restTemplate = restTemplate;
        this.couponService = couponService;
    }

    /**
     * 创建报名记录
     */
    public String createApplyRecord(String activityId, String userId) {
        //判断是不是报了名了
        Boolean aBoolean = checkApply(userId, activityId);
        if(aBoolean){
            return "请勿重复报名";
        }
        Activity activity = activityRepository.findById(activityId).get();
        //查询报名的人数 和等级
        int peopleNum = Integer.parseInt(activity.getPeopleNum());
        System.out.println(peopleNum);

       //查询报名人数
        int i = checkRecordNum(activityId);
        System.out.println("i++++"+i);
        if(i<peopleNum){
            ActivityApply activityApply = new ActivityApply();
            activityApply.setId(UUIDGenerator.getUUID());
            activityApply.setActivityId(activityId);
            activityApply.setUserId(userId);
            activityApply.setCreateTime(DateUtils.currentDate());
            activityApply.setRemove(0);
            activityApplyRepository.saveAndFlush(activityApply);

            //发送消息推送
            Map<String, Object> properties = new HashMap<>();
            properties.put("userId", userId);
            properties.put("type", "activity");
            properties.put("activityName",activity.getActivityName());


            //将计算结果放到MQ队列去补充明细的余额
            String msg = "发消息推送积分变动";
            String exchange = "send.exchange";
            String routingKey = "send.message";
//            rabbitSender.sendMessageToMQ(msg, properties, exchange, routingKey);


            //判断是否要发券
            Integer sendCoupon = activity.getSendCoupon();
            if(sendCoupon ==1){
                String couponId = activity.getCouponId();
                CouponRequest couponRequest = new CouponRequest();
                couponRequest.setUserId(userId);
                couponRequest.setId(couponId);
                String s = couponService.sendCoupon(couponRequest);
            }
            return "报名成功";
        }
        return "报名名额已满";




    }

    /**
     * 分页查询所有报名记录
     *
     * @param page
     * @param size
     * @param keyword
     * @param activityId
     * @return
     */
    public PageDTO<ActivityApplyDTO> findAllActivityApplys(Integer page, Integer size, String activityId, String keyword) {
        List<ActivityApplyDTO> activityApplyDTOS = new ArrayList<>();
        List<ActivityApply> activityApplies = new ArrayList<>();
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<ActivityApply> paged = activityApplyRepository.findAll((Specification<ActivityApply>) (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (StringUtil.isNotEmpty(keyword)) {
                IdDTO idDTO1 = new IdDTO();
                idDTO1.setKeyWord(keyword);
                UserInfoDTO userInfoDTO = restTemplate.postForObject("http://QUANQUAN-USER/user/queryListByKeyword", idDTO1, UserInfoDTO.class);
                List<UserDTO> userDTOS = userInfoDTO.getUserDTOS();
                if (userDTOS.size() > 0) {
                    UserDTO userDTO = userDTOS.get(0);
                    predicates.add(cb.equal(root.get("userId").as(String.class), userDTO.getId()));
                }

            }


            predicates.add(cb.equal(root.get("remove").as(Integer.class), 0));
            predicates.add(cb.equal(root.get("activityId").as(String.class), activityId));

            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        }, pageable);


        activityApplies = paged.getContent();

        //用户id
        List<String> userIds = activityApplies.parallelStream().map(ActivityApply::getUserId).collect(Collectors.toList());
        IdDTO idDTO = new IdDTO();
        idDTO.setForeignKeyIds(userIds);

        UserInfoDTO userInfoDTO = restTemplate.postForObject("http://QUANQUAN-USER/user/query_by_id_list", idDTO, UserInfoDTO.class);
        List<UserDTO> userDTOS = userInfoDTO.getUserDTOS();
        for (ActivityApply activityApply1 : activityApplies) {
            for (UserDTO userDTO : userDTOS) {
                if ((activityApply1.getUserId()).equals(userDTO.getId())) {
                    ActivityApplyDTO activityApplyDTO = new ActivityApplyDTO();
                    //通过映射关系来赋值 //TODO 断点看一下
                    BeanUtils.copyProperties(activityApply1, activityApplyDTO);
                    activityApplyDTO.setPhone(userDTO.getPhone());
                    activityApplyDTO.setMemberName(userDTO.getMemberName());
                    activityApplyDTOS.add(activityApplyDTO);
                }
            }


        }
        PageDTO<ActivityApplyDTO> pageDTO = new PageDTO<>();
        pageDTO.setTotal(paged.getTotalElements());
        pageDTO.setList(activityApplyDTOS);
        pageDTO.setTotalPage(paged.getTotalPages());
        pageDTO.setPage(page);
        pageDTO.setPageSize(size);
        pageDTO.setKeyword(keyword);
        return pageDTO;
    }


    /**
     * 我的报名活动
     *
     * @param page
     * @param size
     * @param userId
     * @return
     */
    public List<ActivityApply> findAllActivityApplysByuserId(Integer page, Integer size, String userId) {

        List<ActivityApply> activityApplies = new ArrayList<>();

        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page, size, sort);
        ActivityApply activityApply = new ActivityApply();
        activityApply.setRemove(0);
        activityApply.setActivityId(userId);
        Example<ActivityApply> example = Example.of(activityApply);
        Page<ActivityApply> findAll = activityApplyRepository.findAll(example, pageable);
        activityApplies = findAll.getContent();
        return activityApplies;
    }


    /**
     * 查看用户是否报名参加活动
     *
     * @return
     */
    public Boolean checkApply(String userId, String activityId) {
        ActivityApply activityApply = activityApplyRepository.findByActivityIdAndUserIdAndRemove(activityId, userId, 0);
        if (activityApply == null) {
            return false;
        } else {
            return true;
        }
    }


    public int checkRecordNum(String activityId){
        List<ActivityApply> all = activityApplyRepository.findByActivityId(activityId);
        int size = all.size();
        return size;
    }

    public PageDTO<ActivityApplyDTO> findAllApply(ActivityApplyRequestBody requestBody) {


        String activityId = requestBody.getActivityId();
        Integer size = requestBody.getSize();
        Integer page = requestBody.getPage();
        String keyword = requestBody.getKeyword();

        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page, size, sort);

        Page<ActivityApply> all = activityApplyRepository.findAll((Specification<ActivityApply>) (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (StringUtil.isNotEmpty(keyword)) {
                IdDTO idDTO1 = new IdDTO();
                idDTO1.setKeyWord(keyword);
                UserInfoDTO userInfoDTO = restTemplate.postForObject("http://QUANQUAN-USER/user/query_keyword", idDTO1, UserInfoDTO.class);
                if (userInfoDTO != null) {
                    List<UserDTO> users = userInfoDTO.getUserDTOS();
                    if (users.size() > 0) {
                        DTO.user.UserDTO userDTO = users.get(0);
                        predicates.add(cb.equal(root.get("userId").as(String.class), userDTO.getId()));
                    }
                }
            }

            predicates.add(cb.equal(root.get("remove").as(Integer.class), 0));
            predicates.add(cb.equal(root.get("activityId").as(String.class), activityId));


            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        }, pageable);

        List<ActivityApplyDTO> activityApplyDTOS = new ArrayList<>();

        List<ActivityApply> activityApplies = all.getContent();


        //用户id
        List<String> userIds = activityApplies.parallelStream().map(ActivityApply::getUserId).collect(Collectors.toList());
        IdDTO idDTO = new IdDTO();
        idDTO.setForeignKeyIds(userIds);

        UserInfoDTO userInfoDTO = restTemplate.postForObject("http://QUANQUAN-USER/user/query_by_id_list", idDTO, UserInfoDTO.class);
        List<UserDTO> userDTOS = userInfoDTO.getUserDTOS();
        for (ActivityApply activityApply1 : activityApplies) {
            for (UserDTO userDTO : userDTOS) {
                if ((activityApply1.getUserId()).equals(userDTO.getId())) {
                    ActivityApplyDTO activityApplyDTO = new ActivityApplyDTO();
                    //通过映射关系来赋值 //TODO 断点看一下
                    BeanUtils.copyProperties(activityApply1, activityApplyDTO);
                    activityApplyDTO.setActivityApplyId(activityApply1.getId());
                    activityApplyDTO.setPhone(userDTO.getPhone());
                    activityApplyDTO.setMemberName(userDTO.getMemberName());
                    activityApplyDTOS.add(activityApplyDTO);
                }
            }


        }

        PageDTO<ActivityApplyDTO> pageDTO = new PageDTO<>();
        pageDTO.setTotal(all.getTotalElements());
        pageDTO.setList(activityApplyDTOS);
        pageDTO.setTotalPage(all.getTotalPages());
        pageDTO.setPage(page);
        pageDTO.setPageSize(size);
        pageDTO.setKeyword(keyword);

        return pageDTO;
    }
}
